package com.maoslv.security;

import com.maoslv.pojo.User;
import com.maoslv.service.user.UserService;
import com.maoslv.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CancellationException;

//登录查询数据库
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserService userService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User loginUser = userService.getByUsername(username);
        if (loginUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        if (loginUser.getState() == false) {
            request.setAttribute("exception", "该用户以注销");
            throw new UsernameNotFoundException("");
        }

        return new CustomUser(loginUser.getId(),
                loginUser.getUsername(),
                loginUser.getPassword(),
                getUserAuthority(loginUser.getId()));
    }

    //获取用户权限信息(角色、菜单列表)
    public List<GrantedAuthority> getUserAuthority(Integer id) {
        String authority = null;
        if (redisUtil.get(id + "-jurisdiction") == null) {
            authority = userService.getUserAuthority(id);
            redisUtil.set(id + "-jurisdiction", authority);
        } else {
            authority = (String) redisUtil.get(id + "-jurisdiction");
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
